import React from 'react';
import { Modal, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import EditForm from '../EditForm';
import {add} from '@/services/Budget';


class AddModal extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isShowModal: false,
      isLoading: false
    };
    this.contentRef = React.createRef();
  }

  /* 监听打开弹框按钮 */
  onShowModal = () => {
    this.setState({ isShowModal: true })
  }

  /* 监听取消按钮 */
  onCancel = () => {
    this.setState({ isShowModal: false })
  }

  /* 提交数据 */
  onConfirm = async () => {
    try {
      const props = this.props;
      const {validateFields, resetFields} = this.contentRef.current;
      const values = await validateFields();
      this.setState({isLoading: true});
      await add(values);
      this.setState({ isShowModal: false });
      resetFields();
      props.add ? props.add() : null;
    } catch (e) {
      console.error('新增学校：', e);
    } finally {
      this.setState({isLoading: false});
    }
  }

  render() {
    const isShowModal = this.state.isShowModal;
    const isLoading = this.state.isLoading;
    const children = this.props.children;
    const contentRef = this.contentRef;
    return (
      <div>
        <Button type="primary" onClick={this.onShowModal} icon={<PlusOutlined />}>{children}</Button>
        <Modal
          title="新增分拨预算"
          okText="确定"
          width="50vw"
          visible={isShowModal}
          confirmLoading={isLoading}
          onCancel={this.onCancel}
          onOk={this.onConfirm}>
          <EditForm ref={contentRef} />
        </Modal>
      </div>
    );
  }
};

export default AddModal
